package nl.moviefan.site.authentication;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.moviefan.site.model.MoviefanRole;
import nl.moviefan.site.model.MoviefanUser;
import nl.moviefan.site.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *
 *
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = Logger.getLogger(UserDetailsServiceImpl.class.getName());

    @Autowired
    private UserRepository userRepo;

    /**
     * Locates the user based on the username. In the actual implementation, the
     * search may possibly be case insensitive, or case insensitive depending on
     * how the implementation instance is configured. In this case, the
     * UserDetails object that comes back may have a username that is of a
     * different case than what was actually requested..
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {

        MoviefanUser user = userRepo.findByUsername(username);

        if (user == null) {
            log.log(Level.WARNING, "username bestaat nietttt");
        }

        Set<MoviefanRole> setje = new HashSet(user.getMoviefanUserRoles());
        List<GrantedAuthority> authorities = buildUserAuthority(setje);

        return buildUserForAuthentication(user, authorities);
    }

    // Converts MoviefanUser to
    // org.springframework.security.core.userdetails.User
    private User buildUserForAuthentication(MoviefanUser user,
            List<GrantedAuthority> authorities) {
        return new User(user.getUsername(),
                user.getPassword(), user.isEnabled(),
                true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<MoviefanRole> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (MoviefanRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getMoviefanRole()));
        }

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;
    }
}
